const express = require('express');
const router = express.Router();
const Task = require('../models/Task');
const cron = require('node-cron');
const { sendToGroups } = require('../utils/wechatApi');

// Create a new task
router.post('/', async (req, res) => {
  try {
    const task = new Task(req.body);
    await task.save();

    // Schedule the task
    cron.schedule(task.scheduleTime.toISOString(), async () => {
      try {
        await sendToGroups(task.groups, task.content, task.mediaId, task.textContent);
        task.status = 'executed';
        await task.save();
      } catch (error) {
        task.status = 'failed';
        await task.save();
      }
    });

    res.status(201).send(task);
  } catch (error) {
    res.status(400).send(error);
  }
});

// Get all tasks
router.get('/', async (req, res) => {
  try {
    const tasks = await Task.find();
    res.send(tasks);
  } catch (error) {
    res.status(500).send(error);
  }
});

// Update a task
router.put('/:id', async (req, res) => {
  try {
    const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!task) return res.status(404).send();

    // Reschedule the task
    cron.schedule(task.scheduleTime.toISOString(), async () => {
      try {
        await sendToGroups(task.groups, task.content, task.mediaId, task.textContent);
        task.status = 'executed';
        await task.save();
      } catch (error) {
        task.status = 'failed';
        await task.save();
      }
    });

    res.send(task);
  } catch (error) {
    res.status(400).send(error);
  }
});

module.exports = router;